﻿using UnityEngine;
using TMPro;
using DG.Tweening;
namespace Client.Hotfix
{
    public class MessageToast 
    {
        public GameObject entity;
        public RectTransform rectTransform;
        public TextMeshProUGUI messageText;
        public CanvasGroup canvasGroup;

        public System.Action<MessageToast> OnFadeComplete;
        public Vector2 TargetPosition { get; set; }
        // 初始化池对象
        public void InitializePoolItem(GameObject entity)
        {
            this.entity = entity;
            rectTransform = entity.GetComponent<RectTransform>();
            canvasGroup = entity.GetComponent<CanvasGroup>();
            messageText = entity.GetComponentInChildren<TextMeshProUGUI>();
            canvasGroup.alpha = 0;
            messageText.text = "";
            TargetPosition = Vector2.zero;
        }

        // 重置状态（返回池时调用）
        public void ResetState()
        {
            canvasGroup.alpha = 0;
            messageText.text = "";
            TargetPosition = Vector2.zero;
            OnFadeComplete = null;
        }

        public void Initialize(string content, float displayDuration, float fadeTime)
        {
            messageText.text = content;
            float width = content.Length * messageText.fontSize;
            rectTransform.sizeDelta = new Vector2(width+30, rectTransform.rect.height);
            FadeInOut(displayDuration, fadeTime);
        }

        private void FadeInOut(float displayDuration, float fadeTime)
        {
            Sequence sequence = DOTween.Sequence();
            sequence.onComplete = ()=> { OnFadeComplete?.Invoke(this); };
            sequence.Append(canvasGroup.DOFade(1, fadeTime).From(0));
            sequence.AppendInterval(displayDuration);
            sequence.Append(canvasGroup.DOFade(0, fadeTime).From(1));
        }
    }

}
